<template>
  <view>
    <view class="form-container">
      <!-- 头部返回+标题 -->
      <view>
        <view
          style="position: absolute; top: 110rpx; left: 30rpx"
          @click="goBack"
        >
          <u-icon name="arrow-left" color="white" size="30"></u-icon>
        </view>
        <view class="header">
          <text class="header-title" v-if="form.company_type == 2"
            >找工程公司需求</text
          >
          <text class="header-title" v-if="form.company_type == 3"
            >发布物资采购需求</text
          >
          <text class="header-title" v-if="form.company_type == 4"
            >发布设计需求</text
          >
          <text class="header-title" v-if="form.company_type == 5"
            >发布监理需求</text
          >
          <text class="header-title" v-if="form.company_type == 6"
            >发布劳务需求</text
          >
          <text class="header-subtitle"
            >请完善以下信息，我们将为您精准匹配</text
          >
        </view>
      </view>

      <view class="form-wrapper">
        <u--form
          :model="form"
          ref="dataForm"
          labelPosition="left"
          :rules="dynamicRules"
          labelWidth="200rpx"
          :labelStyle="{ color: '#333', fontWeight: '500', fontSize: '28rpx' }"
        >
          <view class="form-section">
            <view class="section-title">
              <u-icon name="grid" color="#4A90E2" size="32"></u-icon>
              <text class="section-text">项目基本信息</text>
            </view>
            <u-form-item
              prop="need_title"
              :borderBottom="false"
              v-if="form.company_type != 3"
            >
              <view class="xingX">
                <text class="xing">*</text>
                <text>项目名称</text>
              </view>
              <u--input
                v-model="form.need_title"
                placeholder="请输入项目名称"
                placeholderStyle="color: #999;"
                :customStyle="{ fontSize: '28rpx' }"
              />
            </u-form-item>
            <u-form-item prop="goods_name" :borderBottom="false" v-else>
              <view class="xingX">
                <text class="xing">*</text>
                <text>采购物资名称</text>
              </view>
              <u--input
                v-model="form.goods_name"
                placeholder="请输入采购物资名称"
                placeholderStyle="color: #999;"
                :customStyle="{ fontSize: '28rpx' }"
              />
            </u-form-item>
            <!-- 第一项：物资名称/工程类型/劳务类型/设计业务类型/监理业务类型 -->
            <u-form-item
              prop="need_type"
              :borderBottom="false"
              v-if="form.company_type != 3"
            >
              <view class="xingX">
                <text class="xing">*</text>
                <text>{{ projectNameLabel.need_type }}</text>
              </view>
              <u--input
                v-model="form.need_type"
                :placeholder="'请输入' + projectNameLabel.need_type"
                placeholderStyle="color: #999;"
                :customStyle="{ fontSize: '28rpx' }"
              />
            </u-form-item>
            <u-form-item
              v-if="form.company_type != 3"
              prop="need_amount"
              :borderBottom="false"
            >
              <view class="xingX">
                <text class="xing">*</text>
                <text>{{ projectNameLabel.need_amount }}</text>
              </view>
              <u--input
                v-model="form.need_amount"
                type="digit"
                prefix="¥"
                :placeholder="`请输入${projectNameLabel.need_amount}（元）`"
                placeholderStyle="color: #999;"
                :customStyle="{ fontSize: '28rpx' }"
              />
            </u-form-item>
            <!-- 第二项：规格（仅物资采购显示） -->
            <u-form-item
              v-if="form.company_type == 3"
              prop="goods_attr"
              :borderBottom="false"
            >
              <view class="xingX">
                <text class="xing">*</text>
                <text>物资明细</text>
              </view>
              <u--input
                v-model="form.goods_attr"
                placeholder="请输入物资明细"
                placeholderStyle="color: #999;"
                :customStyle="{ fontSize: '28rpx' }"
              />
            </u-form-item>

            <!-- 第三项：数量（仅物资采购显示） -->
            <u-form-item
              v-if="form.company_type == 3"
              prop="goods_num_img"
              :borderBottom="false"
            >
              <!-- <view class="xingX">
                <text class="xing">*</text>
                <text>清单上传</text>
              </view>
              <u--input
                v-model="form.goods_num_img"
                placeholder="请输入清单上传"
                placeholderStyle="color: #999;"
                :customStyle="{ fontSize: '28rpx' }"
              /> -->
              <view class="xingX">
                <text class="xing">*</text>
                <text>营业执照</text>
              </view>
              <view class="upload-tips" v-if="form.goods_num_img.length == 0">
                <text>请上传清晰营业执照:</text>
              </view>
              <u-upload
                :fileList="form.goods_num_img"
                @afterRead="onChooseAvatar"
                @delete="handleDelete"
                name="unlimitedUpload"
                multiple
                :maxCount="Infinity"
                accept="image"
              >
                <template #default>
                  <view
                    v-if="form.goods_num_img.length != 10"
                    style="
                      display: flex;
                      flex-direction: column;
                      align-items: center;
                      justify-content: center;
                    "
                  >
                    <u-icon name="plus" size="40"></u-icon>
                    <text>点击上传</text>
                  </view>
                </template>
              </u-upload>
            </u-form-item>

            <!-- 第四项：质量要求/工程详情/施工内容/设计内容/监理内容 -->
            <u-form-item prop="need_yao_qiu" :borderBottom="false">
              <view class="xingX">
                <text class="xing">*</text>
                <text>{{ projectNameLabel.need_yao_qiu }}</text>
              </view>
              <u--textarea
                v-model="form.need_yao_qiu"
                height="120rpx"
                :placeholder="'请输入' + projectNameLabel.need_yao_qiu"
              ></u--textarea>
            </u-form-item>

            <!-- 第五项：供货时间/施工时间/设计时间/监理时间 -->
            <u-form-item prop="need_time" :borderBottom="false">
              <view class="xingX">
                <text class="xing">*</text>
                <text>{{ projectNameLabel.need_time }}</text>
              </view>
              <u--input
                v-model="form.need_time"
                :placeholder="'请输入' + projectNameLabel.need_time"
                placeholderStyle="color: #999;"
                :customStyle="{ fontSize: '28rpx' }"
              />
            </u-form-item>

            <!-- 第六项：付款方式 -->
            <u-form-item prop="need_pay_type" :borderBottom="false">
              <view class="xingX">
                <text class="xing">*</text>
                <text>付款方式</text>
              </view>
              <u--input
                v-model="form.need_pay_type"
                placeholder="请输入付款方式"
                placeholderStyle="color: #999;"
                :customStyle="{ fontSize: '28rpx' }"
              />
            </u-form-item>

            <!-- 第七项：项目所在地 -->
            <u-form-item prop="need_city_code" :borderBottom="false">
              <view class="xingX">
                <text class="xing">*</text>
                <text>项目地点</text>
              </view>
              <u-area-picker
                :show="state.cascaderOn_of"
                :showInput="true"
                v-model="form.need_city_code"
                placeholder="请选择省市区"
                :closeOnClickOverlay="false"
                @close="pickerClose"
                :immediateChange="true"
              ></u-area-picker>
            </u-form-item>

            <!-- <u-form-item prop="need_city_address" :borderBottom="false">
              <view class="xingX">
                <text class="xing">*</text>
                <text>详细地址</text>
              </view>
              <u--input
                v-model="form.need_city_address"
                placeholder="请输入项目详细地址"
                placeholderStyle="color: #999;"
                :customStyle="{ fontSize: '28rpx' }"
              />
            </u-form-item> -->

            <!-- 第八项：对供应商/工程公司/劳务队伍/设计公司/监理公司要求 -->
            <u-form-item prop="company_yao_qiu" :borderBottom="false">
              <view class="xingX">
                <text class="xing">*</text>
                <text>{{ projectNameLabel.company_yao_qiu }}</text>
              </view>
              <u--textarea
                v-model="form.company_yao_qiu"
                height="120rpx"
                :placeholder="`请输入${projectNameLabel.company_yao_qiu}`"
              ></u--textarea>
            </u-form-item>

            <!-- 第九项：信息截止有效期 -->
            <u-form-item prop="need_ent_date" :borderBottom="false">
              <view class="xingX">
                <text class="xing">*</text>
                <text>本信息截止有效期</text>
              </view>
              <view @click="state.validPickerShow = true">
                {{
                  form.need_ent_date ? form.need_ent_date : "选择信息截止日期"
                }}
              </view>
              <u-datetime-picker
                :show="state.validPickerShow"
                v-model="form.need_ent_date"
                :formatter="formatter"
                mode="date"
                @confirm="validPickerConfirm"
                @cancel="state.validPickerShow = false"
              ></u-datetime-picker>
            </u-form-item>
          </view>
        </u--form>

        <!-- 提交按钮 -->
        <view class="submit-section">
          <u-button
            type="primary"
            text="提交需求"
            @click="submitForm"
            shape="circle"
            size="large"
            :customStyle="{
              width: '100%',
              height: '90rpx',
              borderRadius: '45rpx',
              fontSize: '32rpx',
              fontWeight: '500',
              background: 'linear-gradient(135deg, #4A90E2 0%, #357ABD 100%)',
              border: 'none',
              marginTop: '40rpx',
              boxShadow: '0 8rpx 24rpx rgba(74, 144, 226, 0.3)',
            }"
          />
          <text class="tip-text">提交后我们将尽快为您匹配合适的劳务资源</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, toRefs, computed } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import { getResource } from "@/utils/Resource";
import { putSave, getId } from "@/api/project.js";
import { showToast, showLoading, hideLoading, showModal } from "@/utils/toast";
import { formatDate } from "@/utils/date.js";

const dataForm = ref(null);

// 状态管理（统一字段名）
const state = reactive({
  cascaderOn_of: false, // 地区选择器显示状态
  pickerShow: false, // 施工时间选择器显示状态
  validPickerShow: false, // 信息有效期选择器显示状态
  id: null, // 编辑时的项目ID
  form: {
    // goods_name: "",
    company_type: "", // 固定为"劳务需求"类型
    need_title: "", // 项目名称\
    need_type: "",
    need_pay_type: "",
    // need_city_address: "", // 项目详细地址
    need_city_code: "", // 项目地点
    need_time: "", // 施工时间
    goods_attr: "",
    goods_num_img: [],
    need_amount: "", // 预估工程总额
    need_yao_qiu: "", // 工程详情
    company_name: "", // 需求单位
    linkman_realname: "", // 联系人
    linkman_duty: "", // 联系人职务
    linkman_mobile: "", // 联系人电话
    company_yao_qiu: "", // 对工程公司要求
    need_ent_date: "", // 信息有效期
  },
});

const { form } = toRefs(state);

// 动态验证规则
const dynamicRules = computed(() => {
  const type = form.value.company_type;
  let goodsNameLabel = "内容";
  let needYaoQiuLabel = "要求";
  let needTimeLabel = "时间";
  let companyYaoQiuLabel = "要求";

  switch (type) {
    case "2": // 工程公司
      goodsNameLabel = "工程类型";
      needYaoQiuLabel = "工程详情";
      needTimeLabel = "施工时间";
      companyYaoQiuLabel = "对工程公司要求";
      break;
    case "3": // 物资采购
      goodsNameLabel = "采购物资名称";
      needYaoQiuLabel = "质量要求";
      needTimeLabel = "供货时间";
      companyYaoQiuLabel = "对供应商要求";
      break;
    case "4": // 设计公司
      goodsNameLabel = "设计业务类型";
      needYaoQiuLabel = "设计内容";
      needTimeLabel = "设计时间";
      companyYaoQiuLabel = "对设计公司要求";
      break;
    case "5": // 监理公司
      goodsNameLabel = "监理业务类型";
      needYaoQiuLabel = "监理内容";
      needTimeLabel = "监理时间";
      companyYaoQiuLabel = "对监理公司要求";
      break;
    case "6": // 劳务队伍
      goodsNameLabel = "劳务类型";
      needYaoQiuLabel = "施工内容";
      needTimeLabel = "施工时间";
      companyYaoQiuLabel = "对劳务队伍要求";
      break;
  }

  return {
    need_type: [
      { required: true, message: `请输入${goodsNameLabel}`, trigger: "blur" },
    ],
    // goods_name: [
    //   { required: true, message: `请输入物资名称`, trigger: "blur" },
    // ],
    goods_attr:
      type == "3"
        ? [{ required: true, message: "请输入规格", trigger: "blur" }]
        : [],
    need_amount:
      type != "3"
        ? [{ required: true, message: "请输入预估总额", trigger: "blur" }]
        : [],
    need_yao_qiu: [
      { required: true, message: `请输入${needYaoQiuLabel}`, trigger: "blur" },
    ],
    need_title: [
      { required: true, message: `请输入项目名称`, trigger: "blur" },
    ],
    need_time: [
      {
        required: true,
        message: `请输入${needTimeLabel}`,
        trigger: ["blur", "confirm"],
      },
    ],
    need_pay_type: [
      { required: true, message: "请输入付款方式", trigger: "blur" },
    ],
    //  need_city_code: [
    //    { required: true, message: "请选择项目地点", trigger: "change" },
    //  ],
    // need_city_address: [
    //   { required: true, message: "请输入详细地址", trigger: "blur" },
    // ],
    company_yao_qiu: [
      {
        required: true,
        message: `请输入${companyYaoQiuLabel}`,
        trigger: "blur",
      },
    ],
    need_ent_date: [
      {
        required: true,
        message: "请选择信息有效期",
        trigger: ["blur", "confirm"],
      },
    ],
    need_title: [
      { required: true, message: "请输入项目名称", trigger: "blur" },
    ],
    company_name: [
      { required: true, message: "请输入需求单位", trigger: "blur" },
    ],
    linkman_realname: [
      { required: true, message: "请输入联系人", trigger: "blur" },
    ],
    linkman_mobile: [
      { required: true, message: "请输入联系电话", trigger: "blur" },
    ],
  };
});

const projectNameLabel = computed(() => {
  switch (form.value.company_type) {
    case "2":
      return {
        need_type: "工程类型",
        need_amount: "预估工程费总额",
        need_yao_qiu: "工程详情",
        need_time: "施工时间",
        company_yao_qiu: "对工程公司要求",
      };
    case "3":
      return {
        need_type: "采购物资名称",
        need_amount: "预估采购费总额",
        need_time: "供货时间",
        need_yao_qiu: "质量要求",
        company_yao_qiu: "对供应商质量要求",
      };
    case "4":
      return {
        need_type: "设计业务类型",
        need_amount: "预估设计费总额",
        need_time: "设计时间",
        need_yao_qiu: "设计内容",
        company_yao_qiu: "对设计公司要求",
      };
    case "5":
      return {
        need_type: "监理业务类型",
        need_amount: "预估监理费总额",
        need_time: "监理时间",
        need_yao_qiu: "监理内容",
        company_yao_qiu: "对监理公司要求",
      };
    case "6":
      return {
        need_type: "劳务类型",
        need_amount: "预估劳务费总额",
        need_time: "施工时间",
        need_yao_qiu: "施工内容",
        company_yao_qiu: "对劳务公司要求",
      };
    default:
      return {
        need_type: "工程类型",
        need_amount: "预估劳务费总额",
        need_time: "工程时间",
        need_yao_qiu: "施工内容",
        company_yao_qiu: "对工程公司要求",
      };
  }
});

// 页面加载（编辑时回显数据）
onLoad(async (e) => {
  if (e.id) {
    // 编辑场景：根据ID获取数据回显
    state.id = e.id;
    await init();
  }
  if (e.type) {
    form.value.company_type = e.type;
  }
});

// 编辑时回显数据（字段名已统一，直接赋值）
const init = async () => {
  try {
    showLoading("加载中...");
    dataForm.value?.resetFields();
    const res = await getId({ id: state.id });
    hideLoading();
    console.log(res.data);
    form.value = res.data;
  } finally {
    hideLoading();
  }
};

// 提交表单
const submitForm = async () => {
  if (!form.value.need_city_code) {
    showToast("请选择项目地点");
    return;
  }

  dataForm.value
    .validate()
    .then(async (valid) => {
      if (valid) {
        console.log("表单验证通过:", form.value);
        try {
          showLoading("提交中...");
          const res = await putSave(state.form);
          hideLoading();
          if (res.code == 10000) {
            // showToast("提交成功");
            showModal(
              {
                title: "系统消息",
                content: "您的需求已提交，审核通过方可查看",
                showCancel: false, // 隐藏取消按钮
              },
              (result) => {
                if (result.error) {
                  uni.showToast({ title: "通知显示失败", icon: "none" });
                  return;
                }
                goBack();
              }
            );

            // setTimeout(() => {
            //   goBack();
            // }, 1500);
          } else {
            showToast(res.message || "提交失败，请重试");
          }
        } catch (error) {
          hideLoading();
          showToast("网络错误，请重试");
          console.error("提交错误:", error);
        }
      } else {
        showToast("请检查表单是否填写完整");
      }
    })
    .catch(() => {
      showToast("请检查表单是否填写完整");
    });
};

const pickerClose = (e) => {
  console.log(e);
};

// 信息有效期选择器确认
const validPickerConfirm = (e) => {
  form.value.need_ent_date = formatDate(new Date(e.value), "YYYY-MM-DD");
  state.validPickerShow = false;
};

const goBack = () => {
  uni.navigateBack({
    delta: 1,
  });
};

const formatter = (type, value) => {
  if (type === "year") {
    return `${value}年`;
  }
  if (type === "month") {
    return `${value}月`;
  }
  if (type === "day") {
    return `${value}日`;
  }
  return value;
};

const onChooseAvatar = async (e) => {
  try {
    const newFiles = e.file;

    const listUrl = await uploadFilePromise(newFiles[0].url);

    form.value.goods_num_img = [
      {
        url: listUrl.web_url,
        web_url: listUrl.url,
      },
    ];
  } catch (err) {
    showToast("获取图片失败，请重试");
  }
};
// 上传文件到服务器
const uploadFilePromise = (filePath) => {
  return new Promise((resolve, reject) => {
    uni.uploadFile({
      url: `${import.meta.env.VITE_API_URL}/upload/image`,
      filePath: filePath,
      name: "file",
      header: {
        Authorization: "Bearer " + uni.getStorageSync("token"),
        "content-type": "multipart/form-data; charset=utf-8",
      },
      formData: {
        type: "avatar",
        file_type: "4",
      },
      success: (res) => {
        const data = JSON.parse(res.data);
        if (data.code == 10000 && data.data?.url) {
          resolve(data.data);
        } else {
          reject(new Error(data.msg || "上传失败"));
        }
      },
      fail: (err) => {
        reject(err);
      },
    });
  });
};
</script>

<style scoped>
:deep(.u-grid-item) {
  align-items: baseline !important;
}
</style>

<style lang="scss" scoped>
.xingX {
  width: 200rpx;
  display: flex;
  align-content: center;
}
.xing {
  color: red;
  margin-right: 4rpx;
}

.form-container {
  min-height: 100vh;
  background: linear-gradient(180deg, #f8f9fa 0%, #ffffff 100%);
  padding-bottom: 40rpx;
}

.header {
  background: linear-gradient(135deg, #4a90e2 0%, #357abd 100%);
  padding: 100rpx 40rpx 40rpx;
  text-align: center;
  color: white;

  .header-title {
    display: block;
    font-size: 40rpx;
    font-weight: bold;
    margin-bottom: 16rpx;
  }

  .header-subtitle {
    font-size: 26rpx;
    opacity: 0.9;
    line-height: 1.4;
  }
}

.form-wrapper {
  margin: 0 30rpx;
  background: white;
  border-radius: 24rpx;
  padding: 40rpx 30rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.06);
}

.form-section {
  margin-bottom: 40rpx;

  &:last-child {
    margin-bottom: 0;
  }
}

.section-title {
  display: flex;
  align-items: center;
  margin-bottom: 30rpx;
  padding: 0 10rpx;

  .section-text {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
    margin-left: 16rpx;
  }
}

.submit-section {
  margin-top: 60rpx;
  text-align: center;

  .tip-text {
    display: block;
    color: #999;
    font-size: 24rpx;
    margin-top: 20rpx;
  }
}

// 输入框样式优化
:deep(.u-input) {
  font-size: 28rpx !important;
  color: #333 !important;
}

// 占位符样式
:deep(.u-input__input) {
  color: #333 !important;

  &::placeholder {
    color: #999 !important;
  }
}
</style>
